//
//  FlutterBaichuanHandle.swift
//  flutter_baichuan
//
//  Created by dmcb on 2021/8/25.
//

import Foundation
import WindmillWeaver

private let errorCodeKey = "errorCode"
private let errorMessageKey = "errorMessage"
private let dataKey = "data"

class FlutterBaichuanHandle: NSObject {
    var channel: FlutterMethodChannel?
    var loginService: AlibcTradeUltimateLoginService {
        return AlibcTradeUltimateSDK.sharedInstance().loginService()
    }

    init(channel: FlutterMethodChannel) {
        super.init()
        self.channel = channel
    }

    var rootViewController: UIViewController {
        if let rootVC = UIApplication.shared.windows.first?.rootViewController {
            return rootVC
        }
        if let rootVC = UIApplication.shared.keyWindow?.rootViewController {
            return rootVC
        }
        return UIViewController()
    }

    /// 初始化
    /// - Parameters:
    ///   - call: FlutterMethodCall
    ///   - result: FlutterResult
    func initAlibc(call: FlutterMethodCall, result: @escaping FlutterResult) {
        AlibcTradeUltimateSDK.sharedInstance().asyncInit {
            WMLHandlerFactory.registerHandler(ALITradeDemoZipArchiver(), with: TRVZipArchiveProtocol.self)

            #if DEBUG
                AlibcTradeUltimateSDK.sharedInstance().enableLocalDebug(true)
                AlibcTradeUltimateSDK.sharedInstance().setDebugLogOpen(true)
            #endif
            let dic = [errorCodeKey: "0", errorMessageKey: "success", "utdid": UTDevice.utdid()]
            result(dic)

        } failure: { error in
            let code = (error as? NSError)?.code ?? -1
            let msg = error.localizedDescription
            let dic = [errorCodeKey: "\(code)", errorMessageKey: msg, "utdid": UTDevice.utdid()]
            result(dic)
        }
    }

    /// 是否已登录
    func isLogin(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        let state = loginService.isLogin()
        result(state)
    }

    /// 是否已登录
    func getUtdid(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        let utdid = UTDevice.utdid()
        result(utdid)
    }

    /// 淘宝授权登录
    /// - Parameters:
    ///   - call: FlutterMethodCall
    ///   - result: FlutterResult
    func loginTaoBao(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        let isLogin = loginService.isLogin()
        if isLogin {
            let userInfo = loginService.getUser()
            let dict: Dictionary<String, Any> = [
                errorCodeKey: "0",
                errorMessageKey: "success",
                dataKey: [
                    "nick": userInfo?.nick ?? "",

                    "avatarUrl": userInfo?.avatarUrl ?? "",
                    "openId": userInfo?.openId ?? "",
                    "openSid": userInfo?.openSid ?? "",
                    "topAccessToken": userInfo?.topAccessToken ?? "",
                    "topAuthCode": userInfo?.topAuthCode ?? ""],
            ]

            #if DEBUG
                print("loginTaoBao-userInfo", dict)
            #endif
            result(dict)

        } else {
            loginService.setH5Only(false)
            loginService.auth(rootViewController) { userInfo in

                let dict: Dictionary<String, Any> = [
                    errorCodeKey: "0",
                    errorMessageKey: "success",
                    dataKey: [
                        "nick": userInfo?.nick ?? "",
                        "avatarUrl": userInfo?.avatarUrl ?? "",
                        "openId": userInfo?.openId ?? "",
                        "openSid": userInfo?.openSid ?? "",
                        "topAccessToken": userInfo?.topAccessToken ?? "",
                        "topAuthCode": userInfo?.topAuthCode ?? ""],
                ]
                #if DEBUG
                    print("loginTaoBao-userInfo", dict)
                #endif

                result(dict)

            } failure: { error in

                let errorCode = (error as NSError?)?.code ?? -1
                let errorMsg = error?.localizedDescription ?? "淘宝授权登录失败"
                let dic = [errorCodeKey: "\(errorCode)", errorMessageKey: errorMsg]
                result(dic)
            }
        }
    }

    /// 获取访问token
    /// - Parameters:
    ///   - call: FlutterMethodCall
    ///   - result: FlutterResult
    func getAccessToken(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        let appKey = call.getString(key: "appKey")
        let appName = call.getString(key: "appName")
        AlibcTradeUltimateSDK.sharedInstance().tradeService().authorize4AppKey(appKey, appName: appName, appLogo: UIImage(named: "mfhk_logo_circle"), currentVC: rootViewController) { error, accessToken, expire in

            let dict: Dictionary<String, Any> = [
                "error": error?.localizedDescription ?? "token获取失败",
                "accessToken": accessToken ?? "",
                "expire": expire ?? "",
            ]
            result(dict)
        }
    }

    /// 退出登录
    /// - Parameters:
    ///   - call: FlutterMethodCall
    ///   - result: FlutterResult
    func loginOut(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        loginService.logout()
    }

    func openByCode(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        let urlP = AlibcTradeUrlParams()
        // 商品id
        urlP.id = call.getString(key: "id")

        let showP = AlibcTradeShowParams()
        showP.linkKey = "taobao"
        showP.isPushBCWebView = false

        let taokeP = AlibcTradeTaokeParams()
        // 淘客ID
        taokeP.pid = call.getString(key: "pid")
        // 渠道id
        taokeP.relationId = call.getString(key: "relationId")
        taokeP.materialSourceUrl = ""

        print("root-vc", rootViewController)

        let code = "suite://bc.suite.basic/bc.template.detail"

        AlibcTradeUltimateSDK.sharedInstance().tradeService().openTradePage(byCode: code, parentController: rootViewController, urlParams: urlP, showParams: showP, taoKeParams: taokeP, trackParam: [:]) { error, data in

            print("--openByCode--", error ?? "--", data ?? [:])
        }
    }

    func openByUrl(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        let url = call.getString(key: "url")

        let urlP = AlibcTradeUrlParams()
        // 商品id
        urlP.id = call.getString(key: "id")

        let showP = AlibcTradeShowParams()
        showP.linkKey = "taobao"
        showP.isPushBCWebView = false

        let taokeP = AlibcTradeTaokeParams()
        // 淘客ID
        taokeP.pid = call.getString(key: "pid")
        // 渠道id
        taokeP.relationId = call.getString(key: "relationId")

        AlibcTradeUltimateSDK.sharedInstance().tradeService().openTradeUrl(url, parentController: rootViewController, showParams: showP, taoKeParams: taokeP, trackParam: [:]) { error, data in
            print("--openByUrl--", error ?? "--", data ?? [:])
        }
    }
}
